package com.example.designpatterns.facade;

import com.example.designpatterns.facade.subsystem.*;

/**
 * 计算机外观类 - 提供一个简单统一的接口，屏蔽子系统的复杂性
 */
public class ComputerFacade {
    // 子系统组件
    private final BIOS bios;
    private final CPU cpu;
    private final Memory memory;
    private final HardDrive hardDrive;
    private final OS os;
    
    // 启动所需的常量
    private static final long BOOT_SECTOR = 0;
    private static final int BOOT_SECTOR_SIZE = 512;
    private static final long KERNEL_LOCATION = 2048;
    private static final int MEMORY_BASE = 0;
    
    public ComputerFacade() {
        this.bios = new BIOS();
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
        this.os = new OS();
    }
    
    /**
     * 启动计算机的简化接口
     */
    public void start() {
        System.out.println("\n=== 启动计算机 ===\n");
        
        // BIOS启动过程
        bios.powerOn();
        bios.selfTest();
        bios.initHardware();
        
        // 加载引导程序
        bios.loadBootLoader();
        cpu.freeze();
        hardDrive.seekTrack(0);
        byte[] bootData = hardDrive.read(BOOT_SECTOR, BOOT_SECTOR_SIZE);
        memory.load(MEMORY_BASE, bootData);
        cpu.jump(MEMORY_BASE);
        cpu.execute();
        
        // 加载操作系统
        cpu.freeze();
        byte[] osData = hardDrive.read(KERNEL_LOCATION, 8192);
        memory.load(1024, osData);
        cpu.jump(1024);
        cpu.unfreeze();
        os.loadKernel();
        os.startServices();
        os.showDesktop();
        
        System.out.println("\n=== 计算机启动完成 ===");
    }
    
    /**
     * 关闭计算机的简化接口
     */
    public void shutdown() {
        System.out.println("\n=== 关闭计算机 ===\n");
        
        os.shutdownServices();
        memory.clear();
        cpu.freeze();
        bios.powerOff();
        
        System.out.println("\n=== 计算机已关闭 ===");
    }
    
    /**
     * 运行程序的简化接口
     */
    public void runProgram(String programName) {
        System.out.println("\n=== 运行程序: " + programName + " ===\n");
        
        // 模拟程序执行过程
        // 假设的程序加载位置
        long programAddress = 4096;
        // 模拟程序数据
        byte[] programData = new byte[1024];
        
        cpu.freeze();
        memory.load(programAddress, programData);
        cpu.jump(programAddress);
        cpu.unfreeze();
        cpu.execute();
        
        System.out.println("程序 " + programName + " 执行完毕");
    }
} 